<template>
    <nly-content-wrapper class="content-warpper-2">
        <div class="content-header-2" >
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2" >
                            <div class="btns" @click="addItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                         <a-col :span="2" >
                            <div class="btns" @click="editItemFun">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                         <a-col :span="2" >
                            <div class="btns" @click="batchDelete">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col :span="2" >
                            <div class="btns" @click="closeTask">
                                <a-icon class="btns-icon" type="close-circle" />
                                <div class="btns-text">关闭</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="reLoadData">
                                <a-icon class="btns-icon" type="file-sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                         
                        
                    </a-col>
                </a-row>
            </div>
            
        </div>
        <nly-content>
            <condition-box ref="myConditionBox" @callBack="ConditionBoxCallBack"></condition-box>
            <!-- 任务列表 -->
            <a-table :columns="columns" :data-source="data" bordered :scroll="{ x: 1000, y: 500}" :pagination="pagination" :row-selection="rowSelection"  @change="onTableChange" :loading="false">
                <div slot="taskName" slot-scope="text, record" @click="goToCalling(record)">
                    {{text}}
                </div>
                <div slot="startTime" slot-scope="text, record" @click="goToCalling(record)">
                    {{text}}
                </div>
                <div slot="endTime" slot-scope="text, record" @click="goToCalling(record)">
                    {{text}}
                </div>
                <div slot="voiceId" slot-scope="text, record" :title="record.voiceName">
                    {{record.voiceName}}
                    <!-- <audio  v-if="record.voiceUrl" :src="record.voiceUrl"  controls="controls" :title="record.voiceName"></audio> -->
                </div>

                <div slot="voiceUrl" slot-scope="text, record">
                     <!-- 播放 -->
                    <span v-if="record.voiceUrl" @click="audioTableControl($event,record)" ><a-icon type="play-circle" style="color:green;"/></span>
                    <!-- 暂停 -->
                    <span v-if="record.voiceUrl" @click="audioTableControl($event)" style="margin-left:10px;"><a-icon type="pause-circle" style="color:green;"/></span>
                    <!-- <audio  v-if="record.voiceUrl" :src="record.voiceUrl"  controls="controls" :title="record.voiceName"></audio> -->
                </div>
                
                <!-- 操作 -->
                <a slot="operation" slot-scope="text, record" >
                    <a-row>
                        <a-button type="primary" size="small" @click="goToDetail($event,record)">详情</a-button>
                    </a-row>
                </a>
                <div slot="statusFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                    <a-radio-group v-model="postData.status" @change="onConditionChange" style="flex-direction: column;">
                        <a-radio :style="radioStyle" :value="null">
                        所有
                        </a-radio>
                        <a-radio :style="radioStyle" :value="0">
                        未开始
                        </a-radio>
                        <a-radio :style="radioStyle" :value="1">
                        进行中
                        </a-radio>
                        <a-radio :style="radioStyle" :value="2">
                        已完成
                        </a-radio>
                        <a-radio :style="radioStyle" :value="3">
                        未完成
                        </a-radio>
                    </a-radio-group>
                </div>
                <div slot="businessStatusFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                    <a-radio-group v-model="postData.businessStatus" @change="onConditionChange" style="flex-direction: column;">
                        <a-radio :style="radioStyle" :value="null">
                        所有
                        </a-radio>
                        <a-radio :style="radioStyle" :value="0">
                        正常
                        </a-radio>
                        <a-radio :style="radioStyle" :value="1">
                        关闭
                        </a-radio>
                    </a-radio-group>
                </div>
                <div slot="createUserNameStatusFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                    <input-group-search 
                        :modalTitle="'选择'+column.title"
                        labelStyle="display: none;"
                        :checkable="true"
                        class="ml-1 mb-2"
                        treeType="officeUser"
                        v-model="postData.createUserIds"
                        @input="onConditionChange"
                    ></input-group-search>
                </div>
            </a-table>
            <audio ref="voiceTableAudio" src="" controls="controls" preload  hidden></audio>
           <!-- 新建任务 -->
            <add-task-modal ref="addTaskModal" @callBack="addTaskCallBack"></add-task-modal>
        </nly-content>  
        <!-- 任务明细 抽屉 -->
        <calldrawer :dataItem="taskItem" :drawerVisible.sync="visible" @reload="pageList"></calldrawer>
    </nly-content-wrapper>
</template>

<script>
import moment from "moment";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import  calldrawer  from '@/components/Crm/calldrawer.vue'
import { mapState } from "vuex";
import { FormInput, EditableCell } from "@/components/Form";
import { addTask, pageList as taskPage, batchDelete ,closeTask } from "@/api/crm/call/callTask";
import { pageList as voicePageList,deleteVoice } from "@/api/crm/call/callVoice";
import addTaskModal from "@/views/crm/call/addTaskModal";
import conditionBox from '@/components/Crm/conditionBox';

export default {
    components: {
        FormInput,
        EditableCell,
        calldrawer,
        addTaskModal,
        conditionBox
    },
    data () {
        
        //查询条件
        const conditionData = [
            {
                id: 1,
                sysName:"任务名称",
                name:"任务名称",
                code:"taskName",
                type:"文本",
                val:"",
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            
            {
                id: 2,
                sysName:"联系类型",
                name:"联系类型",
                code:"taskType",
                type:"下拉选择",
                val:'[{"key": 1, "title": "销售联系"}, {"key": 2, "title": "客户关怀"}, {"key": 3, "title": "售后回访"}, {"key": 4, "title": "投诉回访"}, {"key": 5, "title": "服务支持"}, {"key": 6, "title": "维修维护"}, {"key": 7, "title": "客户投诉"}]',
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            {
                id: 3,
                sysName:"快呼方式",
                name:"快呼方式",
                code:"callType",
                type:"下拉选择",
                val:'[{"key": 1, "title": "人工"}, {"key": 2, "title": "去电放音"}]',
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            {
                id: 4,
                sysName:"业务状态",
                name:"业务状态",
                code:"businessStatus",
                type:"下拉选择",
                val:'[{"key": 0, "title": "正常"}, {"key": 1, "title": "关闭"}]',
                dataType: 1,
                onOff: true,
                isSearch:true
            },
             {
                id: 5,
                sysName:"状态",
                name:"状态",
                code:"status",
                type:"下拉选择",
                val:'[{"key": 0, "title": "未开始"}, {"key": 1, "title": "进行中"}, {"key": 2, "title": "已完成"}, {"key": 3, "title": "未完成"}]',
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            {
                id: 6,
                sysName:"坐席",
                name:"坐席",
                code:"createUserIds",
                type:"搜索选择",
                val:"officeUser",
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            {
                id: 7,
                sysName:"创建日期",
                name:"创建日期",
                code:"createData",
                type:"时间",
                val:"",
                dataType: 1,
                onOff: true,
                isSearch:true
            },
            
        ]
        const columns = [
            //工序信息table
            {
                align: "left",
                title: "任务名称",
                dataIndex: "taskName",
                width: 150,
                scopedSlots: { customRender: 'taskName' },
            },
             {
                align: "center",
                title: "任务开始时间",
                dataIndex: "startTime",
                width: 120,
                scopedSlots: { customRender: 'startTime' },
            },
             {
                align: "center",
                title: "任务结束时间",
                dataIndex: "endTime",
                width: 120,
                scopedSlots: { customRender: 'endTime' },
            },
            {
                align: "left",
                title: "外呼方式",
                dataIndex: "callType",
                width: 70,
                 customRender: (text, row, index) => {
                    const type = ["人工", "去电放音"];
                    return type[text - 1];
                }
            },
            {
                align: "left",
                title: "放音文件",
                dataIndex: "voiceId",
                width: 200,
                scopedSlots: { customRender: 'voiceId' },
            },
            {
                align: "center",
                title: "试听",
                dataIndex: "voiceUrl",
                width: 60,
                scopedSlots: { customRender: 'voiceUrl' },
            },
            {
                align: "center",
                title: "联系类型",
                dataIndex: "taskType",
                width: 70,
                customRender: (text, row, index) => {
                    const type = ["销售联系", "客户关怀","售后回访","投诉回访","服务支持","维修维护","客户投诉"];
                    return type[text - 1];
                }
            },
            {
                align: "center",
                title: "任务条数",
                dataIndex: "mobileCount",
                width: 60,
            },
            {
                align: "center",
                title: "执行数量",
                dataIndex: "dialedCount",
                width: 60,
            },
            {
                align: "center",
                title: "任务执行率",
                dataIndex: "taskType",
                width: 80,
                customRender: (text, row, index) => {
                    if(!row.dialedCount)return '--';
                    let callRate = ((row.dialedCount / row.mobileCount)*100).toFixed(2);
                    return callRate+"%";
                }
            },
              {
                align: "center",
                title: "未呼叫量",
                dataIndex: "waitCount",
                width: 70,
                 customRender: (text, row, index) => {
                    return row.mobileCount - row.dialedCount;
                }
            },
            {
                align: "center",
                title: "任务接通率",
                dataIndex: "taskConnectCount",
                width: 80,
                customRender: (text, row, index) => {
                    if(!row.taskConnectCount)return '--';
                    let callRate = ((row.taskConnectCount / row.dialedCount)*100).toFixed(2);
                    return callRate+"%";
                }
            },
             {
                align: "center",
                title: "状态",
                dataIndex: "status",
                width: 60,
                customRender: (text, row, index) => {
                    const statusArr = ["未开始", "进行中","已完成","未完成"];
                    return statusArr[text];
                },
                scopedSlots: {
                    filterDropdown: 'statusFilterDropdown',
                    // filterIcon: 'statusFilterIcon',
                },
            },
            {
                align: "center",
                title: "业务状态",
                dataIndex: "businessStatus",
                width: 80,
                customRender: (text, row, index) => {
                    const resultTex = !text ? <sapn style="color: green">正常</sapn>: <sapn style="color: red">关闭</sapn> ;
                    return resultTex;
                },
                scopedSlots: {
                    filterDropdown: 'businessStatusFilterDropdown',
                    // filterIcon: 'statusFilterIcon',
                },
            },
            {
                align: "center",
                title: "坐席",
                dataIndex: "createUserName",
                width: 70,
                scopedSlots: {
                    filterDropdown: 'createUserNameStatusFilterDropdown',
                    // filterIcon: 'statusFilterIcon',
                },
            },
            {
                align: "center",
                title: "创建时间",
                dataIndex: "createDate",
                width: 120,
            },
            {
                align: "center",
                title: "操作",
                dataIndex: "operation",
                width: 80,
                scopedSlots: { customRender: 'operation' },
            },
        ];

        const treeData = [];

        return {
            conditionData,
            visible: false,
            taskItem:{},    
            isDisabled: false,
            autoExpandParent: true,
            expandedOfficeKeys: [],
            checkedOfficeKeys: [], //office tree默认选中的key
            selectedOfficeKeys: [],
            officeName: "", //车间id
            officeId: [], //车间名称
            treeData,
            stationData: [],
            teamData: [],
            officeTreeData: [],
            expand: false,
            postData: {
                status:null,
                page:{
                    "current": 1,
                    "size": 20
                }
            },
            selectedKeys: [], //工序table选中key
            selectedData: [],
            pagination: {
                defaultPageSize: 20,
                size: "small",
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            customClick: (record, index) => ({
                on: {
                    click: (event) => {
                        console.log("外呼任务列表，行事件",record,index);
                        event.preventDefault();
                        //跳转 呼叫中心
                        this.goToCalling(record);
                    },
                },
            }),
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            roleData: [],
            columns,
           
            editItem: {
                startTimeMoment: moment(),
            }, //新增/编辑对象
            //------------音频----------------
            voiceUploadUrl:this.$Global.ApiBaseUrl + '/crm/callVoice/uploadVoice',
            voiceSelect:"",         //选择的值
            voiceSelectData:[],     //所有值
            voiceMap:new Map(),     //音频Map 存储
            uploadHeaders:{},       //音频上传 请求头部
            voice_pay: false,       // 语音播放
            dateFormat: "YYYY-MM-DD HH:mm", //任务时间格式
            rangMoment: [], 
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },
        };
    },
    created(){
        this.pageList();
        const token = Vue.ls.get(ACCESS_TOKEN);
        if (token) {
            this.uploadHeaders[ACCESS_TOKEN] = token; 
        }
        
    },
    mounted(){
        let initData = {
            orgDataSource:JSON.parse(JSON.stringify(this.conditionData)),
            dataSource:this.conditionData,
            reportCode:"callTask"
        }
        this.$refs.myConditionBox.initCondition(initData);
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
        rowSelection() {
            let { userInfo } = this;
            return {
                columnWidth:30,
                selectedRowKeys:this.selectedKeys,
                onChange: this.userSelection,
                getCheckboxProps: record => ({
                    props: {
                        disabled: userInfo.id != record.createUserId || record.businessStatus !== 0, 
                    },
                }),
            };
        },
    },
    watch: {
        $route: {
            handler (nv, ov) {
                //离开路由关闭 右侧详情抽屉
                this.visible = false;
            },
            deep: true
        },
    },
    methods: {
        moment,
        reLoadData(){
            Object.assign(this.postData,
            {
                status: null,
                businessStatus: null,
                createUserName: null,
            })
            this.pageList();
        },
        //跳转到 任务详情
        goToDetail (e,item) {
            window.event? window.event.cancelBubble = true : e.stopPropagation();
            this.taskItem = item;
            this.visible = true;

        },
        //跳转到 呼叫中心
        goToCalling (item) {
            const { permissions } = this;
            this.$router.push(`/crm/call/simpleTaskCalling/${item.id}`)
        },
        // 关闭右侧弹窗
        onClose_first() {
            this.visible = false;
        },
         //点击分页
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                page:{
                    size:pagination.pageSize,
                    current: pagination.current,
                }
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.pageList();
        },
        //改变 分页大小
        changePageSize (e) {
            const value = e.target.value;

            Object.assign(this.postData, {
                page:{
                    size: value,
                    current: 1,
                }
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value),
                current: 1,
            });
            this.pageList();
        },
        userSelection (keys, rows) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            this.selectedData = rows;
        },
        //任务列表 播放/暂停
        audioTableControl(e,item){
            window.event? window.event.cancelBubble = true : e.stopPropagation();
            let voiceTableAudio = this.$refs.voiceTableAudio;
            console.log("播放table音频",voiceTableAudio);
            if(voiceTableAudio){
                if(item){
                    voiceTableAudio.src = item.voiceUrl;
                    voiceTableAudio.play();// 播放
                    return;
                }else{
                     voiceTableAudio.pause();// 暂停
                }
            }
        },
        //新增
        addItem () {
            let editItem = {
                startTimeMoment: moment(),
                taskName:null,
                callType:1,
                intervalTime:15,
                sdCallTimes:3,
                voiceid:null,
                voiceUrl:null
            };
            this.$refs.addTaskModal.openTaskModal(editItem);
        },
        //编辑
        editItemFun () {
             if (this.selectedKeys.length != 1) {
                this.$message.warning('请选择一条任务');
                return;
            }
            let item = this.selectedData[0];
            if(item.businessStatus == 1){
                this.$message.warning('任务已经关闭，不能修改');
                return;
            }
            if(item.startTime){
                item.startTimeMoment = moment(item.startTime);
            }
            if( item.endTime){
                item.endTimeMoment = moment(item.endTime);
            }
            let editItem = {...item};
            this.$refs.addTaskModal.openTaskModal(editItem);
            // this.editItem = {...item};
            console.log("编辑时，任务时间",editItem.startTimeMoment,editItem.endTimeMoment);

        },
        //获取任务列表
        pageList () {
            const { postData } = this;
            taskPage(postData).then(response => {
                console.log("获取外呼任务列表", response);
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.data = records;
                    this.data.forEach(item => {
                        item.key = item.id;
                    });
                    Object.assign(this.pagination, {
                        total,
                        current,
                        pageSize: size
                    });
                }
            }).catch(error => { });
        },
        //批量删除 任务
        batchDelete () {
            let _this = this;
            if (this.selectedKeys.length < 1) {
                this.$message.warning('请选择任务');
                return;
            }
             this.$confirm({
                title: '确认',
                content: <span>您确定要{<span style='color:red;'>删除</span>}这些记录吗？</span>,
                onOk () {
                     batchDelete(_this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            _this.$message.success("删除成功");
                            _this.selectedKeys = [];
                            _this.selectedData = [];
                            //刷新 列表
                            _this.pageList();
                        }
                    });
                },
                onCancel () { },
            });
           
        },
        //批量关闭 任务
        closeTask () {
            let _this = this;
            if (this.selectedKeys.length < 1) {
                this.$message.warning('请选择任务');
                return;
            }
             this.$confirm({
                title: '确认',
                content: <span>您确定要{<span style='color:red;'>关闭</span>}这些任务吗？</span>,
                onOk () {
                     closeTask(_this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            _this.$message.success("关闭成功");
                            _this.selectedKeys = [];
                            _this.selectedData = [];
                            //刷新 列表
                            _this.pageList();
                        }
                    });
                },
                onCancel () { },
            });
           
        },
        //保存任务后回调
        addTaskCallBack(){
            this.pageList();
        },
        //条件改变
        onConditionChange(){
            Object.assign(this.postData.page,{current:1});
            this.pageList();
        },
        //查询方案回调
        ConditionBoxCallBack(data){
            let size =  this.postData.page.size;
            if(data)
            this.postData = data;
            Object.assign(this.postData, {
                page:{
                    size,
                    current: 1,
                }
            });
            this.pageList();
        }
       
    }
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }

    
</style>
<style lang="less">
    // @import '~@/style/setting/inventory.less';
 
</style>